const express = require("express");
const multer = require("multer");
const pool = require("./pool");
const cors = require('cors');
const fs = require("fs");
const app = express();
const bodyParser = require("body-parser");

app.use(cors());
const jwt = require("jsonwebtoken");
const { json } = require("body-parser");

app.use(express.static("www"));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
    extended: true
}));

const diskStorage = multer.diskStorage({
    destination: "./www/imgs",
    filename: function (req, file, cb) {
        // console.log(req.body);
        // console.log(cb);
        let name = Date.now();
        let arr = file.originalname.split(".");
        let extname = arr[arr.length - 1];
        let photoName = name + "." + extname;
        req.body.photo = "imgs/" + photoName;
        cb(null, photoName);
    }
})
const upload = multer({
    storage: diskStorage
});
const goodsimg = multer.diskStorage({
    destination: "./www/goodsimg",
    filename: function (req, file, cb) {
        // console.log(req.body);
        // console.log(file);
        let name = Date.now();
        let arr = file.originalname.split(".");
        let extname = arr[arr.length - 1];
        let photoName = name + "." + extname;
        if (req.body.imgs==undefined) {
             req.body.imgs=[]
             req.body.imgs.push( "goodsimg/" + photoName) 
            cb(null, photoName);
        }else{
        req.body.imgs.push( "goodsimg/" + photoName) 
        cb(null, photoName);
    }
}
})
const goods= multer({
    storage: goodsimg
});
app.get("/api/user", (req, res) => {
    const {
        username,
        password
    } = req.query
    pool.query("select * from users where username=?", [username], (error, result) => {
        if (result.length == 0) {
            res.json({
                code: 0,
                msg: "账号不存在"
            })
            return
        } else if (result[0].password == password) {
            let token = jwt.sign({
                username: username
            }, 'helloworld', {
                expiresIn: 60 * 60 * 24 * 7
            })
            res.json({
                code: 1,
                token
            })
            return
        } else if (!(result[0].password == password)) {
            res.json({
                code: 2,
                msg: "密码错误"
            })
            return
        }

    })
})
app.get("/api/token",(req,res)=>{
    const {token}=req.query
    jwt.verify(token, "helloworld", (error, decoded) => {
        if (error) {
            res.json({
                code: 0,
                msg: "token校验失败，请重新登录"
            })
        }else{
            res.json({
                code: 1,
                msg: "token校验成功"
            })
        }
    })
})
app.post("/api/lunboadd", upload.single("imgs"), (req, res) => {
    const {token,photo}=req.body
    jwt.verify(token, "helloworld", (error, decoded) => {
        if (error) {
            res.json({
                code: 0,
                msg: "token校验失败，请重新登录"
            })
            return;
        }
        pool.query("insert into carouselimgs (url)values(?)", [photo], (error, result) => {
            res.json({
                code: 1,
                msg: "添加成功",
                url:"http://localhost:3001/"+req.body.photo
            })
        })
    })
})
app.get("/api/lunbodelete", upload.single("photo"), (req, res) => {
    let {token,photo}=req.query
    photo=photo.replace("http://localhost:3001/",'')
    jwt.verify(token, "helloworld", (error, decoded) => {
        if (error) {
            res.json({
                code: 0,
                msg: "token校验失败，请重新登录"
            })
            return;
        }
        pool.query("Delete from carouselimgs where url=?", [photo], (error, result) => {
            if (error) {
                res.json({
                    code: 0,
                    msg: "删除失败",
                })
            }else{
            fs.unlinkSync("./www/" + photo);
            res.json({
                code: 1,
                msg: "删除成功",
            })}
        })
    })
})
app.get("/api/lunbo", (req, res) => {
    pool.query("select * from carouselimgs", (error, result) => {
        const url = []
        result.map((i, index) => {
            url[index] = "http://localhost:3001/"+i.url
        })
        res.json({
            url
        })
    })
})
app.get("/api/fenleione", (req, res) => {
    pool.query("select * from type_one", (error, result) => {
        const type = []
        result.map((i, index) => {
            type[index] = i.type_one
        })
        res.json({
            type
        })
    })
})
app.get("/api/typeoneadd", (req, res) => {
    const {token,type}=req.query
    jwt.verify(token, "helloworld", (error, decoded) => {
        if (error) {
            res.json({
                code: 0,
                msg: "添加失败"
            })
        }else{
            pool.query("insert  into  type_one  values(?)", [type], (error, result) => {
                if (error) {
                    res.json({
                        code: 0,
                        msg: "添加失败"
                    })
                }else{
                    res.json({
                        code:1,
                        mag:"添加成功"
                    })
                }
            })
           
        }
    })
})
app.get("/api/typeonedelete",(req, res) => {
    let {token,photo}=req.query
    jwt.verify(token, "helloworld", (error, decoded) => {
        if (error) {
            res.json({
                code: 0,
                msg: "token校验失败，请重新登录"
            })
            return;
        }
        pool.query("Delete from type_two where type_one=?", [photo], (error, result) => {
            if (error) {
                res.json({
                    code: 0,
                    msg: "删除失败",
                })
            }else{
                pool.query("Delete from type_one where type_one=?", [photo], (error, result) => {
                    if (error) {
                        res.json({
                            code: 0,
                            msg: "删除失败",
                        })
                    }else{
                        res.json({
                            code: 1,
                            msg: "删除成功",
                        })
                    }  
                })
           }
        })
    })
})
app.get("/api/typetwo", (req, res) => {
const {type}=req.query
    pool.query("select type_two from type_two  where type_one=?",[type], (error, result) => {
        const type = []
        result.map((i, index) => {
            type[index] = i.type_two
        })
        res.json({
            type
        })
    })
})
app.get("/api/typetwoadd", (req, res) => {
    const {typeone,typetwo}=req.query
        pool.query("insert  into  type_two (type_one,type_two)  values(?,?)",[typeone,typetwo], (error, result) => {
            if (error) {
                res.json({
                    code:0,
                    msg:"添加失败"
                })
            }else{
                res.json({
                    code:1,
                    msg:"添加成功"
                })
            }
           
        })
})
app.get("/api/typetwodelete",(req, res) => {
    let {token,photo}=req.query
    jwt.verify(token, "helloworld", (error, decoded) => {
        if (error) {
            res.json({
                code: 0,
                msg: "token校验失败，请重新登录"
            })
            return;
        }
        pool.query("Delete from type_two where type_two=?", [photo], (error, result) => {
            if (error) {
                res.json({
                    code: 0,
                    msg: "删除失败",
                })
            }else{
                res.json({
                    code: 1,
                    msg: "删除成功",
                })
           }
        })
    })
})
app.get("/api/xiangqing",upload.array("imgs"), (req, res) => {
    pool.query("select * from goods", (error, result) => {
        pool.query("select * from goodimgs", (error, url) => {
            // "http://localhost:3001/"
            url.forEach((i,index,arr)=>{
                arr[index].url="http://localhost:3001/"+i.url
            })

            res.json({
                result,
                url
            })
        })
       
    
    })
})
app.post("/api/goodsimgadd", goods.array("imgs",8), (req, res) => {
    const {token,name,price,typeone,typetwo,imgs}=req.body
    jwt.verify(token, "helloworld", (error, decoded) => {
        if (error) {
            res.json({
                code: 0,
                msg: "token校验失败，请重新登录"
            })
            return;
        }
        pool.query("insert into goods (title,price,type_one,type_two)values(?,?,?,?)", [name,price,typeone,typetwo], (error, result) => {
            const id=result.insertId
            if (error) {
                res.json({
                    code: 2,
                    msg: "添加失败"
                })
                return
            }else{
                let k=[]
                imgs.map((i ,index,arr)=> {
                     pool.query("insert into goodimgs (goodsid,url) values(?,?)", [id,i], (errors, results) => {
                    if (errors) {
                        res.json({
                            code: 2,
                            msg: "添加失败"
                        })
                        return
                    }else{
                        k.push(1)
                        if (k.length==arr.length) {
                            res.json({
                                code: 1,
                                msg: "添加成功",
                            })
                        }
                        
                    }
                })
                });
           }
        })
    })
})
app.get("/api/goodsdelete",(req, res) => {
    let {token,id,img}=req.query
    img.map((i,index,arr)=>{
        arr[index]=i.replace("http://localhost:3001/",'')

    })
    jwt.verify(token, "helloworld", (error, decoded) => {
        if (error) {
            res.json({
                code: 0,
                msg: "token校验失败，请重新登录"
            })
            return;
        }
        pool.query("Delete from goods where id=?", [id], (error, result) => {
            if (error) {
                res.json({
                    code: 0,
                    msg: "删除失败",
                })
            }else{
                pool.query("Delete from goodimgs where goodsid=?", [id], (error, result) => {
                    console.log(error);
                    if (error) {
                        res.json({
                            code: 0,
                            msg: "删除失败",
                        })
                        return
                    }else{
                        img.map((i)=>{
                             fs.unlinkSync("./www/" + i);
                        })
                        res.json({
                            code: 1,
                            msg: "删除成功",
                        })
                    }  
                })
           }
        })
    })
})
app.post("/api/goodxiugai", goods.array("imgs",8), (req, res) => {
    let {token,name,price,typeone,typetwo,imgs,imgobj,id}=req.body
    jwt.verify(token, "helloworld", (error, decoded) => {
        if (error) {
            res.json({
                code: 0,
                msg: "token校验失败，请重新登录"
            })
            return;
        }
          pool.query("select * from goodimgs where goodsid=?", [id], (error, result) => {
            //   删除图片操作
              if (imgobj==undefined) {
                pool.query("Delete from goodimgs where goodsid=?;", [id], (error, result) => {})
              }else{
                const mysqlimg=[]
                result.map((i,index)=>{
                    mysqlimg.push(i.url)
                })
                if (!(imgobj instanceof Array)) {
                   imgobj=imgobj.split()
                }
                imgobj.map((i,index,arr)=>{
                    arr[index]=i.replace("http://localhost:3001/",'')
                })
                const xin=[]
                for (let i = 0; i < mysqlimg.length; i++) {
                    if (imgobj.indexOf(mysqlimg[i])==-1) {
                        xin.push(mysqlimg[i])
                    }
                }
                 if (xin.length>0) {
                     xin.map((i,index)=>{
                          pool.query("Delete from goodimgs where url=?;", [i], (error, result) => {})
                          fs.unlinkSync("./www/" + i);
                     })
                 }
              }
            //  修改数据操作
                pool.query("update goods set title=?,price=?,type_one=?,type_two=? where id=?", [name,price,typeone,typetwo,id], (error, result) => {
                    if (imgs==undefined) {
                        if (!error) {
                            res.json({
                                code: 1,
                                msg: "修改成功",
                            })
                        }else{
                            res.json({
                                code: 2,
                                msg: "修改失败",
                            })
                        }
                    }else{
                        let k=[]
                        imgs.map((i ,index,arr)=> {
                             pool.query("insert into goodimgs (goodsid,url) values(?,?)", [id,i], (errors, results) => {
                            if (errors) {
                                res.json({
                                    code: 2,
                                    msg: "修改失败"
                                })
                                return
                            }else{
                                k.push(1)
                                if (k.length==arr.length) {
                                    res.json({
                                        code: 1,
                                        msg: "修改成功",
                                    })
                                }
                                
                            }
                        })
                        });
                    }
                  
                })
          })
    })
})
app.get("/api/sousuo", (req, res) => {
    const {name,token}=req.query
    console.log(name,token);
    pool.query(`select * from goods where  title like "%${name}%"`,[name], (error, result) => {
        console.log(result);
       
        pool.query("select * from goodimgs", (error, url) => {
            url.forEach((i,index,arr)=>{
                arr[index].url="http://localhost:3001/"+i.url
            })

            res.json({
                result,
                url
            })
        })
    
    })
    })
    
app.listen(3001, () => {
    console.log("服务器运行起来了,监听3001端口");
})